﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Infragistics.Windows.DataPresenter;
using System.ComponentModel;
using System.Data;
using PTExpress.SysLib;
namespace PTExpress.Templates
{
    /// <summary>
    /// Interaction logic for TextBoxComplete.xaml
    /// </summary>
    public partial class TextBoxComplete : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        DataTable _tb = new DataTable();
        DataTable tb = new DataTable();

        public bool IsFocus
        {
            get { return (bool)GetValue(IsFocusProperty); }
            set { SetValue(IsFocusProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsFocus.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsFocusProperty =
            DependencyProperty.Register("IsFocus", typeof(bool), typeof(TextBoxComplete), new UIPropertyMetadata(false));



        public DataRecord RowResult
        {
            get { return (DataRecord)GetValue(RowResultProperty); }
            set { SetValue(RowResultProperty, value); }
        }

        // Using a DependencyProperty as the backing store for RowResult.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RowResultProperty =
            DependencyProperty.Register("RowResult", typeof(DataRecord), typeof(TextBoxComplete), new UIPropertyMetadata(null));


        public bool IsExpanded
        {
            get { return (bool)GetValue(IsExpandedProperty); }
            set { SetValue(IsExpandedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsExpanded.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsExpandedProperty =
            DependencyProperty.Register("IsExpanded", typeof(bool), typeof(TextBoxComplete), new UIPropertyMetadata(false));

        public object ValueItem
        {
            get { return (object)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); OnPropertyChanged("ValueItem"); }
        }

        // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("ValueItem", typeof(object), typeof(TextBoxComplete), new UIPropertyMetadata(null));

        public string DisplayItemPath
        {
            get { return (string)GetValue(DisplayItemPathProperty); }
            set { SetValue(DisplayItemPathProperty, value); }
        }

        public string ValueItemPath
        {
            get { return (string)GetValue(ValueItemPathProperty); }
            set { SetValue(ValueItemPathProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ValueItemPath.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ValueItemPathProperty =
            DependencyProperty.Register("ValueItemPath", typeof(string), typeof(TextBoxComplete), new UIPropertyMetadata(null));

        public bool IsSelectChange
        {
            get { return (bool)GetValue(IsSelectChangeProperty); }
            set { SetValue(IsSelectChangeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsSelectChange.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsSelectChangeProperty =
            DependencyProperty.Register("IsSelectChange", typeof(bool), typeof(TextBoxComplete), new UIPropertyMetadata(false));
        // Using a DependencyProperty as the backing store for DisplayItemPath.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DisplayItemPathProperty =
            DependencyProperty.Register("DisplayItemPath", typeof(string), typeof(TextBoxComplete), new UIPropertyMetadata(null));


        public string MaDm
        {
            get { return (string)GetValue(MaDmProperty); }
            set { SetValue(MaDmProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MaDm.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MaDmProperty =
            DependencyProperty.Register("MaDm", typeof(string), typeof(TextBoxComplete), new UIPropertyMetadata(""));




        public string StringBrowse
        {
            get { return (string)GetValue(StringBrowseProperty); }
            set { SetValue(StringBrowseProperty, value); }
        }

        // Using a DependencyProperty as the backing store for StringBrowse.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StringBrowseProperty =
            DependencyProperty.Register("StringBrowse", typeof(string), typeof(TextBoxComplete), new UIPropertyMetadata(""));



        public DataTable DataSource
        {
            get { return (DataTable)GetValue(DataSourceProperty); }
            set { SetValue(DataSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DataSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataSourceProperty =
            DependencyProperty.Register("DataSource", typeof(DataTable), typeof(TextBoxComplete), new UIPropertyMetadata(null));


        bool _IsReadOnly;
        public bool IsReadOnly { set { _IsReadOnly = value; OnPropertyChanged("IsReadOnly"); } }


        protected void OnPropertyChanged(string _value)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(_value));
                if (_IsReadOnly)
                    gridMain.IsEnabled = !_IsReadOnly;
            }
        }


        public TextBoxComplete()
        {
            InitializeComponent();
        }

        private void UcTextBoxComplete_Loaded(object sender, RoutedEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                DataGrid.FieldSetting(ref xdgData, StringBrowse);
                xdgData.DataSource = DataSource.DefaultView;
                if (DataSource != null)
                {
                    DataGrid.FieldSetting(ref xdgData, DataSource, StringBrowse);
                }
            }
        }

        private void txtTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            txtTextBox.Background = System.Windows.Media.Brushes.Transparent;
            if (IsSelectChange)
                return;
            if (txtTextBox.Text.Trim() == "?")
            {
                if (DataSource == null)
                    _tb = new DataTable();
                else
                    _tb = DataSource.Copy();
                xdgData.DataSource = _tb.DefaultView;
                //DataGrid.FieldSetting(ref xdgData, StringBrowse);
                //popup.IsOpen = true;
                IsExpanded = true;
                return;
            }
            if (DataSource != null)
            {
                DataRow[] rows = null;
                rows = DataSource.Select(DisplayItemPath + " like '" + txtTextBox.Text + "%'");
                if (rows.Length > 0)
                {
                    _tb = rows.CopyToDataTable();
                    xdgData.DataSource = _tb.DefaultView;
                    //DataGrid.FieldSetting(ref xdgData, StringBrowse);
                    IsExpanded = true;
                    //popup.IsOpen = true;
                }

                else
                {
                    _tb = DataSource.Copy();
                    _tb.Rows.Clear();
                    xdgData.DataSource = _tb.DefaultView;
                    //DataGrid.FieldSetting(ref xdgData, StringBrowse);
                    //popup.IsOpen = true;
                    IsExpanded = true;
                    return;
                }
            }

        }

        private void txtTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (first)
            {
                txtTextBox.SelectAll();
                first = false;
            }
            IsSelectChange = false;
            IsExpanded = false;
            IsFocus = true;
        }

        private void popup_Opened(object sender, EventArgs e)
        {
            //ValueItem = null;
            if (xdgData.Records.Count > 0)
                xdgData.ActiveDataItem = xdgData.Records[0];
            else ValueItem = null;

        }

        //Selected Item
        private void xdgData_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                DataRecord r = xdgData.ActiveRecord as DataRecord;
                if (r == null)
                {
                    ValueItem = null;
                    txtTextBox.Text = "";
                }
                else
                {
                    ValueItem = r.Cells[ValueItemPath].Value;
                    //txtTextBox.Text = r.Cells[DisplayItemPath].Value.ToString();
                }
                IsExpanded = false;
                txtTextBox.Focus();
                txtTextBox.SelectAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            //popup.IsOpen = false;
        }

        //DropDown
        private void txtTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            DataRecord r = xdgData.ActiveRecord as DataRecord;
            if (e.Key == Key.Down)
            {
                IsExpanded = true;
                xdgData.Focus();
                xdgData.ActiveDataItem = xdgData.ActiveRecord;
            }
        }

        //Selected Items
        private void xdgData_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                try
                {
                    DataRecord r = xdgData.ActiveRecord as DataRecord;
                    if (r == null)
                    {
                        ValueItem = null;
                        txtTextBox.Text = "";
                    }
                    else
                    {
                        ValueItem = r.Cells[ValueItemPath].Value;
                        //txtTextBox.Text = r.Cells[DisplayItemPath].Value.ToString();
                    }
                    IsExpanded = false;
                    txtTextBox.Focus();
                    txtTextBox.SelectAll();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                IsExpanded = false;
            }
        }

        //Select Items Change
        private void xdgData_SelectedItemsChanged(object sender, Infragistics.Windows.DataPresenter.Events.SelectedItemsChangedEventArgs e)
        {
            try
            {
                DataRecord r = xdgData.ActiveRecord as DataRecord;
                RowResult = r;
                IsSelectChange = true;
                IsFocus = true;
                if (r == null)
                {
                    ValueItem = null;
                    txtTextBox.Text = "";
                }
                else
                {
                    //ValueItem = r.Cells[ValueItemPath].Value;
                    txtTextBox.Text = r.Cells[DisplayItemPath].Value.ToString();
                }
                //txtTextBox.Text = Value.ToString();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


        private void UcPopup_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            TextBox t = (e.NewFocus as TextBox);
            TextBox t2 = (e.OldFocus as TextBox);
            Button b = (e.NewFocus as Button);
            Infragistics.Windows.DataPresenter.CellValuePresenter c2 = (e.OldFocus as Infragistics.Windows.DataPresenter.CellValuePresenter);
            Infragistics.Windows.DataPresenter.XamDataGrid g = (e.NewFocus as Infragistics.Windows.DataPresenter.XamDataGrid);
            Infragistics.Windows.DataPresenter.DataRecordPresenter r = (e.NewFocus as Infragistics.Windows.DataPresenter.DataRecordPresenter);
            Infragistics.Windows.DataPresenter.CellValuePresenter c = (e.NewFocus as Infragistics.Windows.DataPresenter.CellValuePresenter);
            if (t != null)
            {
                if (t.Name == "txtTextBox" && IsFocus)
                {
                    if (t2 != null)
                    {
                        if (t2.Name == "txtTextBox")
                            IsFocus = false;
                        else
                        {
                            IsExpanded = false;
                            IsFocus = true;
                        }
                    }
                    else
                    {
                        IsExpanded = false;
                        IsFocus = true;
                    }
                    return;
                }
            }
            if (g != null)
            {
                if (g.Name == "xdgData")
                {
                    IsExpanded = true;
                    IsFocus = true;
                }
                return;
            }

            if (r != null)
            {
                XamDataGrid contentHost = SysObj.TryFindParent<XamDataGrid>(r);
                if (contentHost != null)
                    if (contentHost.Name == "xdgData")
                    {
                        IsExpanded = true;
                        IsFocus = true;
                    }
                return;
            }

            if (b != null)
            {
                //IsExpanded = true;
                IsFocus = true;
                return;
            }
            if (c2 != null)
            {
                if (b != null || t != null)
                {
                    IsExpanded = false;
                    IsFocus = false;
                }
            }
            IsFocus = false;
        }

        private void txtTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (!IsFocus)
            {
                IsExpanded = false;

                if (ValueItem == null)
                {
                    e.Handled = true;
                    txtTextBox.Background = System.Windows.Media.Brushes.Red;
                    txtTextBox.CaretIndex = txtTextBox.Text.Length;
                    IsFocus = true;
                }
            }
        }

        public delegate void NewHandler(object sender, RoutedEventArgs e);
        public event NewHandler AddNewItem;
        private void btnThemMoi_Click(object sender, RoutedEventArgs e)
        {
            //if (AddNewItem != null)
            IsExpanded = false;
            AddNewItem(sender, e);

        }

        public void GetFocus()
        {
            txtTextBox.Focus();
            first = true;
        }
        bool first = true;
        //public delegate void Execute();
        //public event Execute AddNewItem;

    }
}
